package com.qinggeng.project.system.service.impl;

import java.util.Date;
import java.util.List;

import com.qinggeng.common.enums.AssistStatusEnum;
import com.qinggeng.common.enums.GoodsTypeEnum;
import com.qinggeng.common.enums.ShowTypeEnum;
import com.qinggeng.common.exception.CustomException;
import com.qinggeng.common.utils.DateUtils;
import com.qinggeng.framework.config.mq.dto.MessageAssistDTO;
import com.qinggeng.framework.web.domain.AjaxResult;
import com.qinggeng.project.api.dto.AssistRecordDto;
import com.qinggeng.project.api.security.utils.ApiUtils;
import com.qinggeng.project.system.domain.AssistMessageRecord;
import com.qinggeng.project.system.domain.Goods;
import com.qinggeng.project.system.mapper.AssistMessageRecordMapper;
import com.qinggeng.project.system.service.IGoodsService;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.qinggeng.project.system.mapper.AssistRecordMapper;
import com.qinggeng.project.system.domain.AssistRecord;
import com.qinggeng.project.system.service.IAssistRecordService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;

/**
 * 助力记录Service业务层处理
 *
 * @author ruoyi
 * @date 2020-11-05
 */
@Slf4j
@Service
public class AssistRecordServiceImpl implements IAssistRecordService
{
    @Resource
    private AssistRecordMapper assistRecordMapper;

    @Resource
    private RedissonClient redissonClient;

    @Resource
    private AssistMessageRecordMapper assistMessageRecordMapper;

    @Autowired
    private IGoodsService goodsService;

    private static final String LOCK_ASSIST_ID_="lock_assist_id_";

    /**
     * 查询助力记录
     *
     * @param id 助力记录ID
     * @return 助力记录
     */
    @Override
    public AssistRecord selectAssistRecordById(Long id)
    {
        return assistRecordMapper.selectAssistRecordById(id);
    }

    @Override
    public AssistRecord selectAssistRecordByIdAndUserId(Long id, Long userId) {
        return assistRecordMapper.selectAssistRecordByIdAndUserId(id,userId);
    }

    /**
     * 查询助力记录列表
     *
     * @param assistRecord 助力记录
     * @return 助力记录
     */
    @Override
    public List<AssistRecord> selectAssistRecordList(AssistRecord assistRecord)
    {
        return assistRecordMapper.selectAssistRecordList(assistRecord);
    }

    /**
     * 新增助力记录
     *
     * @param assistRecord 助力记录
     * @return 结果
     */
    @Override
    public int insertAssistRecord(AssistRecord assistRecord)
    {
        return assistRecordMapper.insertAssistRecord(assistRecord);
    }

    /**
     * 修改助力记录
     *
     * @param assistRecord 助力记录
     * @return 结果
     */
    @Override
    public int updateAssistRecord(AssistRecord assistRecord)
    {
        assistRecord.setUpdateTime(DateUtils.getNowDate());
        return assistRecordMapper.updateAssistRecord(assistRecord);
    }

    /**
     * 批量删除助力记录
     *
     * @param ids 需要删除的助力记录ID
     * @return 结果
     */
    @Override
    public int deleteAssistRecordByIds(Long[] ids)
    {
        return assistRecordMapper.deleteAssistRecordByIds(ids);
    }

    /**
     * 删除助力记录信息
     *
     * @param id 助力记录ID
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int deleteAssistRecordById(Long id)
    {
        return assistRecordMapper.deleteAssistRecordById(id);
    }
    /**
     * 查询正在进行的或成功的助力记录,通过userId和商品id
     * @param userId
     * @param goodsId
     * @return
     */
    @Override
    public AssistRecord selectAssistRecordByUserIdAndGoodsId(Long userId, Long goodsId) {
        return assistRecordMapper.selectAssistRecordByUserIdAndGoodsId(userId,goodsId);
    }
    /**
     * 查询超时助力记录
     * @return
     */
    @Override
    public List<AssistRecord> selectOutTimeAssistRecordList() {
        return assistRecordMapper.selectOutTimeAssistRecordList();
    }
    /**
     * 根据用户id查询当前正在进行中的助力信息
     * @param userId
     * @return
     */
    @Override
    public List<AssistRecord> selectAssistRecordByUserId(Long userId) {
        return assistRecordMapper.selectAssistRecordByUserId(userId);
    }
    /**
     * 查询当前主类是否助力过
     * @param userId
     * @param mainCategory
     * @return
     */
    @Override
    public AssistRecord selectAssistRecordByMainCategory(Long userId, Long mainCategory) {
        return assistRecordMapper.selectAssistRecordByMainCategory(userId,mainCategory);
    }
    /**
     * 查询助力记录列表
     * @param userId
     * @param assistIndex 助力条件
     * @return
     */
    @Override
    public List<AssistRecordDto> selectAssistRecordByUserIdAndAssistIndex(Long userId, String assistIndex) {

        return assistRecordMapper.selectAssistRecordByUserIdAndAssistIndex(userId,assistIndex);
    }

    @Override
    @Transactional
    public void updateAssistRecordForFail(MessageAssistDTO messageAssistDTO) {
        log.info("-------助力失败消息开始------");
        if (messageAssistDTO == null){
            throw new CustomException("助力消息模型不存在");
        }
        RLock lock = redissonClient.getLock(LOCK_ASSIST_ID_ + messageAssistDTO.getId());
        lock.lock();
        try {
            Example example = new Example(AssistMessageRecord.class);
            Example.Criteria criteria = example.createCriteria();
            criteria.andEqualTo("messageId",messageAssistDTO.getMessageId());
            AssistMessageRecord assistMessageRecord = assistMessageRecordMapper.selectOneByExample(example);
            if (assistMessageRecord !=null){
                return;
            }
            //插入消息记录
            assistMessageRecord = new AssistMessageRecord();
            assistMessageRecord.setAssistId(messageAssistDTO.getId());
            assistMessageRecord.setDelayTime(messageAssistDTO.getDelayTime());
            assistMessageRecord.setMessageId(messageAssistDTO.getMessageId());
            assistMessageRecord.setCreateTime(new Date());
            assistMessageRecordMapper.insertSelective(assistMessageRecord);

            AssistRecord assistRecord = assistRecordMapper.selectAssistRecordById(messageAssistDTO.getId());
            if (assistRecord == null){
                throw new CustomException("助力记录不存在");
            }

            //2进行中 助力状态
            if (!"2".equals(assistRecord.getAssistSuccess())){
                return;
            }
            //设置助力状态为失败 0
            assistRecord.setAssistSuccess(AssistStatusEnum.未助力.getStatus());
            assistRecord.setUpdateTime(new Date());
            assistRecordMapper.updateAssistRecord(assistRecord);
        } catch (Exception e) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            e.printStackTrace();
        }finally {
            lock.unlock();
        }
        log.info("-------助力失败消息结束------");
    }

    @Override
    public AssistRecord checkAssistRecord(Long recordId){

        AssistRecord record=assistRecordMapper.selectAssistRecordByIdAndUserId(recordId, ApiUtils.getUserId());

        if(null==record){
            throw new CustomException("未查询到您的好友助力记录！", ShowTypeEnum.用户.getValue());
        }
        //助力成功状态 3=结束
        if(record.getAssistSuccess().equals(AssistStatusEnum.抽奖结束.getStatus())){
           throw new CustomException("您已经抽过奖了哦！",ShowTypeEnum.用户.getValue());
        }
        //助力成功状态不为 1=成功
        if(!record.getAssistSuccess().equals(AssistStatusEnum.助力成功.getStatus())){
            throw new CustomException("您尚未助力成功，请继续加油！",ShowTypeEnum.用户.getValue());
        }
        return record;
    }

    @Override
    public Goods checkAssistGoods(Long goodsId) {
        Goods goods=goodsService.selectGoodsById(goodsId);
        if(null==goods){
            throw new CustomException("助力商品不存在！",ShowTypeEnum.用户.getValue());
        }
        if(!goods.getGoodsType().equals(GoodsTypeEnum.普通商品.getValue())){
            throw new CustomException("商品已售罄",ShowTypeEnum.用户.getValue());
        }
        return goods;
    }

    @Override
    public int updateAssistRecordAssistSuccess(Goods oldGoods) {
        Goods goods=goodsService.selectGoodsById(oldGoods.getGoodsId());
        if(null==goods){
            throw new CustomException("商品不存在");
        }
        if(!oldGoods.getGoodsType().equals(GoodsTypeEnum.普通商品.getValue())
             ||!goods.getGoodsType().equals(GoodsTypeEnum.预售商品.getValue())){
            return 0;
        }
        AssistRecord where=new AssistRecord();
        where.setAssistSuccess(AssistStatusEnum.进行中.getStatus());
        where.setGoodsId(goods.getGoodsId());
        List<AssistRecord> assistRecordList=this.selectAssistRecordList(where);
        int rows=0;
        try{
            for (AssistRecord record:assistRecordList) {
                record.setAssistSuccess(AssistStatusEnum.未助力.getStatus());
                if(this.updateAssistRecord(record)>0){
                    rows++;
                }
            }
        }catch (Exception e){
            log.error("助力状态更新失败："+e.getMessage());
        }
        return rows;
    }
}
